package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.helper.ApiContainer;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolNatureEnum;
import com.jwsoft.manager.common.vo.common.AreaControlVO;
import com.jwsoft.manager.common.vo.eduJhjyQuerySync.EduJhjyQuerySyncKeyVO;
import com.jwsoft.manager.common.vo.eduJhjyQuerySync.EduJhjyQuerySyncQueryVO;
import com.jwsoft.manager.common.vo.eduJhjyQuerySync.EduJhjyQuerySyncVO;
import com.jwsoft.manager.common.vo.eduJhjyQuerySync.JhjyQueryVO;
import com.jwsoft.manager.common.vo.eduSystemConfig.EduSystemConfigFuncQueryVO;
import com.jwsoft.manager.core.dao.model.EduJhjyQuerySync;
import com.jwsoft.manager.core.dao.model.EduStudentEnroll;
import com.jwsoft.manager.core.dao.service.EduJhjyQuerySyncService;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollService;
import com.jwsoft.manager.core.integration.EduJhjyQuerySyncIntegration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * 金华录取查询业务实现类
 *
 * @author wangtao
 * @since 2023-03-16
 */
@ApiService(funcCode = "eduJhjyQuerySync", title = "金华录取查询")
public class EduJhjyQuerySyncIntegrationImpl implements EduJhjyQuerySyncIntegration {

    @Autowired
    public EduJhjyQuerySyncService eduJhjyQuerySyncService;

    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;

    @Autowired
    private CommonIntegration commonIntegration;

    @Autowired
    private EduSystemConfigIntegration eduSystemConfigIntegration;

    @Autowired
    private ApiContainer apiContainer;
    @Autowired
    private EduHelper eduHelper;

    @Override
    @OpApi(funcCode = "eduJhjyQuerySync0001", title = "金华录取查询分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduJhjyQuerySyncVO> getList(EduJhjyQuerySyncQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<EduJhjyQuerySync> list = eduJhjyQuerySyncService.list();
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduJhjyQuerySync> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduJhjyQuerySyncVO> resultList = Convert.toList(EduJhjyQuerySyncVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduJhjyQuerySync0002", title = "金华录取查询根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduJhjyQuerySyncVO getById(EduJhjyQuerySyncKeyVO vo) {
        EduJhjyQuerySync entity = eduJhjyQuerySyncService.getById(vo.getJhjyQueryId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduJhjyQuerySyncVO result = Convert.convert(EduJhjyQuerySyncVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduJhjyQuerySync0003", title = "金华录取查询保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduJhjyQuerySyncVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduJhjyQuerySync0004", title = "金华录取查询新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduJhjyQuerySync0004",
            operationName = "金华录取查询新增",
            dataType = "jhjyQueryId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduJhjyQuerySyncVO add(EduJhjyQuerySyncVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduJhjyQuerySync entity = Convert.convert(EduJhjyQuerySync.class, vo);
        eduJhjyQuerySyncService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setJhjyQueryId(entity.getJhjyQueryId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduJhjyQuerySync0005", title = "金华录取查询修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduJhjyQuerySync0005",
            operationName = "金华录取查询修改",
            dataType = "jhjyQueryId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduJhjyQuerySyncVO edit(EduJhjyQuerySyncVO vo) {
        if (ObjectUtils.isEmpty(vo.getJhjyQueryId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduJhjyQuerySync oldEntity = eduJhjyQuerySyncService.getById(vo.getJhjyQueryId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduJhjyQuerySync entity = Convert.convert(EduJhjyQuerySync.class, vo);
        eduJhjyQuerySyncService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduJhjyQuerySync0006", title = "金华录取查询根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduJhjyQuerySync0006",
            operationName = "金华录取查询删除",
            dataType = "jhjyQueryId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduJhjyQuerySyncKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getJhjyQueryId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduJhjyQuerySync entity = eduJhjyQuerySyncService.getById(vo.getJhjyQueryId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduJhjyQuerySyncService.removeById(vo.getJhjyQueryId());
    }

    @Override
    @OpApi(funcCode = "eduJhjyQuerySync0008", title = "金华录取情况实时查询", funcType = FuncTypeEnum.query)
    public EduJhjyQuerySyncVO query(EduJhjyQuerySyncQueryVO vo) {
        Integer year = eduHelper.thisYear();
        if (StringUtils.isBlank(vo.getAreaCode())) {
            throw new AppException("查询的行政区划不能为空");
        }
        EduStudentEnroll enroll = new EduStudentEnroll();
        enroll.setAreaCode(vo.getAreaCode());
        enroll.setSchoolCategory(vo.getSchoolCategory());
        enroll.setIdcard(vo.getIdcard());
        enroll.setYear(year);
        enroll.setFullName(vo.getName());
        return queryJhjy(enroll);
    }

    @Override
    public EduJhjyQuerySyncVO queryJhjy(EduStudentEnroll enroll) {
        JhjyQueryVO queryVO=new JhjyQueryVO();
        queryVO.setIdcard(enroll.getIdcard());
        if("2".equals(enroll.getSchoolCategory())){
            queryVO.setEduStage(13);
        }else if("3".equals(enroll.getSchoolCategory())){
            queryVO.setEduStage(14);
        }
        EduJhjyQuerySync eduJhjyQuerySync = new EduJhjyQuerySync();
        eduJhjyQuerySync.setName(enroll.getFullName());
        eduJhjyQuerySync.setIdcard(enroll.getIdcard());
        eduJhjyQuerySync.setEduStage(queryVO.getEduStage());
        eduJhjyQuerySync.setYear(enroll.getYear());
        eduJhjyQuerySync.setSyncStatus("0");
        try {
           // String lqdw = jhjyIntegration.unifiedSupervisionEnrollSearchAdmit(queryVO);
            String lqdw = "";
            EduSystemConfigFuncQueryVO funcQueryVO=new EduSystemConfigFuncQueryVO();
            funcQueryVO.setAreaCode(enroll.getAreaCode());
            funcQueryVO.setEduConfigKey("unifiedSupervisionEnrollSearchAdmit");
            String funcCode=eduSystemConfigIntegration.getFuncCode(funcQueryVO);
            ApiModel apiModel=apiContainer.get(funcCode);
            if(apiModel!=null){
                try {
                    Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
                    if (null != bean) {
                        lqdw = apiModel.getMethod().invoke(bean, queryVO).toString();
                    }else {
                        throw new AppException(SessionUtil.getSessionInfo().getAreaCode()+"未找到处理报名保存的个性化方法");
                    }
                }catch (AppException e ){
                    throw e;
                }catch (InvocationTargetException e ){
                    try{
                        AppException exception= (AppException) e.getTargetException();
                        throw new AppException(exception.getMsg(),e.getTargetException());
                    }catch (Exception ex){
                        throw new AppException(e.getCause().getMessage(),e.getTargetException());
                    }

                }catch (Exception e ){
                    throw new AppException( e.getMessage(),e);
                }
            }else {
                throw new AppException(SessionUtil.getSessionInfo().getAreaCode()+"未找到处理报名保存的个性化方法");
            }
            QueryWrapper<EduJhjyQuerySync> querySyncQueryWrapper = new QueryWrapper<>();
            querySyncQueryWrapper.lambda().eq(EduJhjyQuerySync::getIdcard, enroll.getIdcard())
                    .eq(EduJhjyQuerySync::getYear, enroll.getYear());
            List<EduJhjyQuerySync> list = eduJhjyQuerySyncService.list(querySyncQueryWrapper);

            if (!CollectionUtils.isEmpty(list)) {
                eduJhjyQuerySync.setJhjyQueryId(list.get(0).getJhjyQueryId());
                eduJhjyQuerySync.setCreateName(list.get(0).getCreateName());
                eduJhjyQuerySync.setCreateTime(list.get(0).getCreateTime());
            } else {
                eduJhjyQuerySync.setJhjyQueryId(IdUtil.simpleUUID());
            }
            String lqFlag = BoolEnum.FALSE.getType();
            if (StringUtils.isNotBlank(lqdw)) {
                lqFlag = BoolEnum.TRUE.getType();
            } else {
                lqdw = null;
            }
            eduJhjyQuerySync.setLqDw(lqdw);
            eduJhjyQuerySync.setSyncStatus("1");
            eduJhjyQuerySync.setSyncRemarks("比对通过");
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("localLqDw");
            commonVO.setAreaCode(enroll.getAreaCode());
            String localDw = commonIntegration.getValueByKeyAndArea(commonVO);
            if(StringUtils.isBlank(localDw)){
                throw new AppException("请先配置金华教育本地录取单位");
            }
            if (localDw.equals(lqdw)) {
                lqFlag = BoolEnum.FALSE.getType();
                lqdw = null;
            }
            UpdateWrapper<EduStudentEnroll> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(EduStudentEnroll::getIdcard, enroll.getIdcard())
                    .eq(EduStudentEnroll::getYear, enroll.getYear())
                    .set(EduStudentEnroll::getOtherEnrollUnit, lqdw)
                    .set(EduStudentEnroll::getOtherEnrollStatus, lqFlag);
            eduStudentEnrollService.update(updateWrapper);
        }catch (Exception e){
            String msg=e.getMessage();
            if (StringUtils.isNotBlank(msg) && msg.length() > 300) {
                msg=msg.substring(0,200);
            }
            eduJhjyQuerySync.setSyncStatus("2");
            eduJhjyQuerySync.setSyncRemarks(msg);
        }
        eduJhjyQuerySyncService.saveOrUpdate(eduJhjyQuerySync);
        EduJhjyQuerySyncVO retVO=Convert.convert(EduJhjyQuerySyncVO.class,eduJhjyQuerySync);
        return retVO;
    }

    @Override
    public void createJhjySync(AreaControlVO baseVO) {
        QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduStudentEnroll::getYear, eduHelper.thisYear())
                .eq(StringUtils.isNotBlank(baseVO.getAreaCode()), EduStudentEnroll::getAreaCode, baseVO.getAreaCode())
                .eq(EduStudentEnroll::getSchoolNature, SchoolNatureEnum.gb.getType())
                .isNull(EduStudentEnroll::getOtherEnrollStatus);
        PageHelper.startPage(1, 500);
        List<EduStudentEnroll> list = eduStudentEnrollService.list(queryWrapper);
        PageInfo<EduStudentEnroll> enrollPageInfo = new PageInfo<>(list);
        if (!CollectionUtils.isEmpty(enrollPageInfo.getList())) {
            for (EduStudentEnroll eduStudentEnroll : enrollPageInfo.getList()) {
                this.queryJhjy(eduStudentEnroll);
            }
        } else {
            QueryWrapper<EduStudentEnroll> queryMbWrapper = new QueryWrapper<>();
            queryMbWrapper.lambda().eq(EduStudentEnroll::getYear, eduHelper.thisYear())
                    .eq(StringUtils.isNotBlank(baseVO.getAreaCode()), EduStudentEnroll::getAreaCode, baseVO.getAreaCode())
                    .ne(EduStudentEnroll::getSchoolNature, SchoolNatureEnum.gb.getType())
                    .isNull(EduStudentEnroll::getOtherEnrollStatus);
            List<EduStudentEnroll> listMb = eduStudentEnrollService.list(queryMbWrapper);
            if (!CollectionUtils.isEmpty(listMb)) {
                for (EduStudentEnroll eduStudentEnroll : listMb) {
                    this.queryJhjy(eduStudentEnroll);
                }
            }
        }
    }

    @Override
    @OpApi(funcCode = "eduJhjyQuerySync0009", title = "根据证件号查询出最新同步记录", funcType = FuncTypeEnum.query)
    public EduJhjyQuerySyncVO querySyncByIdCard(JhjyQueryVO vo) {
        if (StringUtils.isBlank(vo.getIdcard())){
            throw new AppException("证件号不能为空");
        }
        QueryWrapper<EduJhjyQuerySync> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EduJhjyQuerySync::getIdcard,vo.getIdcard())
                .eq(EduJhjyQuerySync::getYear,eduHelper.thisYear())
                .orderByDesc(EduJhjyQuerySync::getCreateTime);
        if (eduJhjyQuerySyncService.count(queryWrapper) == 0){
            throw new AppException("该学生未同步过，需要进行数据同步");
        }
        EduJhjyQuerySync eduJhjyQuerySync = eduJhjyQuerySyncService.list(queryWrapper).get(0);
        EduJhjyQuerySyncVO result = Convert.convert(EduJhjyQuerySyncVO.class, eduJhjyQuerySync);
        return result;
    }

}
